package com.seqb.utils;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author lilinshen
 * @title 加密工具类
 * @description 请填写相关描述
 * @date 2019/11/11
 */
public class Md5Utils {

    private static final int HASH_ITERATIONS = 2;
    private static final String SALT = "1qazxsw2";
    private static final String ALGORITH_NAME = "md5";

    /**
     * 加密密码
     */
    public static String encrypt(String password) {
        String encryptPassword = null;
        try {
            encryptPassword = new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptPassword;
    }

    /**
     * 加密密码和账号
     */
    public static String encrypt(String username, String password) {
        String encryptPassword = null;
        try {
            encryptPassword = new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(username + SALT), HASH_ITERATIONS).toHex();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptPassword;
    }

    /**
     * 使用md5的算法进行加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }


    /**
     * 使用hex_md5的算法进行加密为32位16进制数
     */
    public static String hexMd5(String source) {
        byte[] data = encode2bytes(source);
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            String hex = Integer.toHexString(0xff & data[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static byte[] encode2bytes(String source) {
        byte[] result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(source.getBytes("UTF-8"));
            result = md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
